package com.zlz.server.config;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.zlz.server.constant.MailConstant;
import com.zlz.server.pojo.MailLog;
import com.zlz.server.service.IMailLogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;

/**
 * @author: zlz
 * @date: 2021/3/16 23:23
 * @description: RabbitMQ配置类
 * @since: JDK1.8
 */
@Configuration
@Slf4j
public class RabbitMQConfig {
    @Resource
    private CachingConnectionFactory cachingConnectionFactory;

    @Resource
    private IMailLogService iMailLogService;

    @Bean
    public RabbitTemplate rabbitTemplate() {
        RabbitTemplate rabbitTemplate = new RabbitTemplate(cachingConnectionFactory);
        /**
         * 消息确认回调,确认消息是否到达broker
         * data:消息唯一标识
         * ack:消息确认结果
         * cause:失败原因
         */
        rabbitTemplate.setConfirmCallback((data, ack, cause) -> {
            String msgId = data.getId();
            if (ack) {
                log.info("{}消息发送成功", msgId);
                iMailLogService.update(new UpdateWrapper<MailLog>().set("status", 1).eq("msg_id", msgId));
            } else {
                log.error("{}消息发送失败", msgId);
            }
        });

        /**
         * 消息失败回调,比如router不到key回调
         * msg：消息主题
         * repCode：响应码
         * repText：相应描述
         * exchange：交换机
         * routingKey：路由key
         */
        rabbitTemplate.setReturnCallback((msg, repCode, repText, exchange, routingKey) -> {
            log.error("消息发送queue时失败, {}", msg.getBody());
        });
        return rabbitTemplate;
    }

    @Bean
    public Queue queue() {
        return new Queue(MailConstant.MAIL_QUEUE_NAME);
    }

    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange(MailConstant.MAIL_EXCHANGE_NAME);
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(directExchange()).with(MailConstant.MAIL_ROUTING_KEY_NAME);
    }
}
